//
//  MyGalleryViewController.m
//  parent
//
//  Created by IreWesT on 15/6/2.
//  Copyright (c) 2015年 ci123. All rights reserved.
//

#import "MyGalleryViewController.h"
#import "MJRefresh.h"
#import "MyGalleryCollectionViewCell.h"

#define kMyGalleryCellIdentifier     @"MyGalleryCollectionCell"

@interface MyGalleryViewController ()<
    UICollectionViewDataSource,
    UICollectionViewDelegate
>

@property (nonatomic, retain) UICollectionView *collectionView;

@property (nonatomic, retain) NSMutableArray *data;
@property (nonatomic, copy) NSString *picPrefix;
@property (nonatomic, assign) CGFloat cellWidth;
@property (nonatomic, assign) CGFloat cellHeight;

@end

@implementation MyGalleryViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    if ([self respondsToSelector:@selector(edgesForExtendedLayout)])
        self.edgesForExtendedLayout = UIRectEdgeNone;
    
    [self _initView];
    [self _initData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)_initView {

    self.title = @"我的相册";
    
    CGFloat gap = 2.5f;
    _cellWidth = (APP_SCREEN_WIDTH - gap * 2) / 3;
    _cellHeight = _cellWidth;
    UICollectionViewFlowLayout *layout  = [[UICollectionViewFlowLayout alloc] init];
    layout.itemSize                     = CGSizeMake(_cellWidth, _cellHeight);
    layout.sectionInset                 = UIEdgeInsetsMake(5, 0, 0, 0);
    layout.minimumInteritemSpacing      = gap;
    layout.minimumLineSpacing           = gap;
    
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, APP_SCREEN_WIDTH, APP_SCREEN_HEIGHT - self.navHeight) collectionViewLayout:layout];
    [self.collectionView registerClass:[MyGalleryCollectionViewCell class]            forCellWithReuseIdentifier:kMyGalleryCellIdentifier];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.backgroundColor = [UIColor whiteColor];
    self.collectionView.bounces = YES;
    self.collectionView.alwaysBounceVertical = YES;
    [self.view addSubview:_collectionView];
    
    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 20 , 44, 44)];
    button.showsTouchWhenHighlighted = YES;
    button.backgroundColor = [UIColor clearColor];
    button.imageEdgeInsets = UIEdgeInsetsMake(0, -10, 0, 0);
    [button setImage:[UIImage imageNamed:@"nav_btn_back"] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(backPage:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];

}

-(void)backPage:(id)button
{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - Private Methods

#pragma mark - Data

- (void)_initData {
    
    _data = [[NSMutableArray alloc] init];
    
    [self setUpRefreshPlugin];
}

- (void)dealData:(NSDictionary *)dic isReload:(BOOL)isReload {
    
    if (!dic || dic.count <=0 || ![dic isKindOfClass:[NSDictionary class]]) {
        return;
    }
    
    if (isReload) {
        [_data removeAllObjects];
    }
    
    _picPrefix = [NSString stringWithFormat:@"%@", dic[@"srcurl"]];
    for (NSDictionary *subDic in dic[@"works"]) {
        [_data addObject:subDic];
    }
    
    [_collectionView reloadData];
}

#pragma mark - MJRefresh

- (void)setUpRefreshPlugin {
    
    // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
    [_collectionView addHeaderWithTarget:self action:@selector(headerRereshing)];
    //#warning 自动刷新(一进入程序就下拉刷新)
    [_collectionView headerBeginRefreshing];
    
    // 2.上拉加载更多(进入刷新状态就会调用self的footerRereshing)
    [_collectionView addFooterWithTarget:self action:@selector(footerRereshing)];
    
    //设置文字(也可以不设置,默认的文字在MJRefreshConst中修改)
    _collectionView.headerPullToRefreshText = @"下拉刷新";
    _collectionView.headerReleaseToRefreshText = @"松开刷新";
    _collectionView.headerRefreshingText = @"正在刷新...";
    
    _collectionView.footerPullToRefreshText = @"上拉加载";
    _collectionView.footerReleaseToRefreshText = @"松开加载";
    _collectionView.footerRefreshingText = @"正在加载...";
}

//================顶部刷新，获取最新动态=========================
//首次进入会自动执行一次获取最新动态
- (void)headerRereshing
{
    if ([NetWorkManager connectedToNetwork]) {
        
        [self apiGetData:@"new" baseId:@"-1"];
    }else{
        //没有网络的情况下，加载本地缓存数据
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"网络连接断开" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
    }
}

//================底部刷新，获取最新动态=========================
- (void)footerRereshing
{
    
    if([NetWorkManager connectedToNetwork]) {
        NSString *baseId = [NSString stringWithFormat:@"%@", ((NSDictionary *)_data.lastObject)[@"id"]];
        NSLog(@"%@", baseId);
        [self apiGetData:@"old" baseId:baseId];
        
    }else{
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"网络连接断开" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
    }
}

-(void) stopHeaderRefresh {
    
    [self.collectionView headerEndRefreshing];
}

-(void) stopFooterRefresh {
    
    [self.collectionView footerEndRefreshing];
}

#pragma mark - Networking

- (BOOL)apiGetData:(NSString*)requestType baseId:(NSString *)baseId{
    

    NSString* uid = [NSString stringWithFormat:@"%ld",[[UserDao getInstance] getUserId]];
    NSString* utype = @"1";
    
    NSDictionary *temp_dict = @{@"uid":uid,
                                @"utype":utype,
                                @"token":[[UserDao getInstance]getAccessToken],
                                @"dir":requestType,
                                @"baseid":baseId};
    
    NSString *dataString = [JsonUtil convertDictionaryToJson:temp_dict];
    
    NSString *msg = @"PARENT_GET_OWN_WORKS";
    
    PopUIManager *popUIMgr = [PopUIManager getInstanse];
    [popUIMgr showWaitingUI:self.view];
    
    [[NetWorkManager getInstanse] requestURLAsynMessage:msg data:dataString FinishBlock:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        
        if ([requestType isEqualToString:@"new"]) {
            [self stopHeaderRefresh];
        }else if ([requestType isEqualToString:@"old"]){
            [self stopFooterRefresh];
        }
        
        if (connectionError) { //连接失败
            NSLog(@"Http Error: %@   %ld", connectionError.localizedDescription,(long)connectionError.code);
            NSString *error_content = [NSString stringWithFormat:@"连接错误:%ld",(long)connectionError.code];
            [popUIMgr popAlertView:nil title:@"提示" message:error_content cancelButtonTitle:@"确定"];
        }else{//连接成功，判断是否有数据返回
            if (data) {
                NSDictionary *dict = [JsonUtil convertDataToDictionary:data];
                if ([[dict objectForKey:@"retCode"] integerValue] == 1) {
                    if ([requestType isEqualToString:@"new"]) { //下拉 获取最新数据的回调
                        NSLog(@"%@", dict);
                        [self dealData:dict isReload:YES];
                    }else if ([requestType isEqualToString:@"old"]){//上拉 加载更多旧数据的回调
                        [self dealData:dict isReload:NO];
                    }
                }else if ([[dict objectForKey:@"retCode"] integerValue]== 10020) {
                    if ([requestType isEqualToString:@"new"]) { //下拉 获取最新数据的回调
                        [popUIMgr popAlertView:nil title:@"提示" message:@"还没有数据哦~" cancelButtonTitle:@"确定"];
                    }else if ([requestType isEqualToString:@"old"]){//上拉 加载更多旧数据的回调
                        [popUIMgr popAlertView:nil title:@"提示" message:@"没有更多了哦~" cancelButtonTitle:@"确定"];
                    }
                }else{
                    [popUIMgr popAlertView:nil title:@"提示" message:@"数据解析错误" cancelButtonTitle:@"确定"];
                }
            }else{
                [popUIMgr popAlertView:nil title:@"提示" message:@"服务器没有返回数据" cancelButtonTitle:@"确定"];
            }
        }
        [popUIMgr removeWaitingUI];
    }];
    return YES;
}

#pragma mark - UICollectionViewDelegate

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    NSLog(@"%@", indexPath);
}

#pragma mark - UICollectionViewDataSource

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    return _data.count;
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    
    return 1;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {

    static NSString * CellIdentifier = kMyGalleryCellIdentifier;
    MyGalleryCollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];
    cell.backgroundColor = [UIColor blackColor];
    cell.picPrefix = _picPrefix;
    cell.data = _data[indexPath.row];
    
    return cell;
}

@end
